package com.lmb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmb.bean.*;
import com.lmb.common.BaseContext;
import com.lmb.dto.OrdersDto;
import com.lmb.dto.SetmealDto;
import com.lmb.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    //客户端

    //用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        //1.调用service处理
        orderService.submit(orders);

        //2.响应数据 "下单成功"
        return R.success("下单成功！");
    }

    //查询所有订单
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize){
        Page<OrdersDto> OrdersDtoPage = orderService.findPage(page, pageSize);
        return R.success(OrdersDtoPage);
    }

    //再来一单
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        //1.获取当前订单id中的订单详情，即菜品/套餐信息
        LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(wrapper1);

        //2.获取当前登录的用户id
        Long userId = BaseContext.getCurrentId();

        //3.将订单的详情转换到购物车中，并加上用户id
        List<ShoppingCart> carts = orderDetails.stream().map(orderDetail -> {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,cart,"id");
            cart.setUserId(userId);
            return cart;
        }).collect(Collectors.toList());

        //4.保存每个cart
        carts.stream().forEach(cart -> {
            shoppingCartService.save(cart);
        });
        return R.success("操作成功");
    }
        /*log.info(orders.toString());
        //设置用户id 指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        //得到订单id
        Long ordersId = orders.getId();
        LambdaQueryWrapper<Orders> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getId,ordersId);
        //根据订单id得到订单元素
        Orders one = orderService.getOne(queryWrapper);
        //得到订单表中的number 也就是订单明细表中的order_id
        String number = one.getNumber();

        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,number);
        //根据订单明细表的order_id得到订单明细集合
        List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
        //新建购物车集合
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        //通过用户id把原来的购物车给清空
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        //遍历订单明细集合,将集合中的元素加入购物车集合
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //得到菜品id或套餐id
            Long dishId = orderDetail.getDishId();
            Long setmealId = orderDetail.getSetmealId();
            //添加购物车部分属性
            shoppingCart.setUserId(currentId);
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            if(dishId!=null){
                //订单明细元素中是菜品
                LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishLambdaQueryWrapper.eq(Dish::getId,dishId);
                //根据订单明细集合中的单个元素获得单个菜品元素
                Dish dishone = dishService.getOne(dishLambdaQueryWrapper);
                //根据菜品信息添加购物车信息
                shoppingCart.setDishId(dishId);
                shoppingCart.setName(dishone.getName());
                shoppingCart.setImage(dishone.getImage());
                //调用保存购物车方法
                shoppingCarts.add(shoppingCart);
            }
            else if(setmealId!=null){
                //订单明细元素中是套餐
                LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                setmealLambdaQueryWrapper.eq(Setmeal::getId,setmealId);
                //根据订单明细集合中的单个元素获得单个套餐元素
                Setmeal setmealone = setmealService.getOne(setmealLambdaQueryWrapper);
                //根据套餐信息添加购物车信息
                shoppingCart.setSetmealId(setmealId);
                shoppingCart.setName(setmealone.getName());
                shoppingCart.setImage(setmealone.getImage());
                //调用保存购物车方法
                shoppingCarts.add(shoppingCart);
            }
        }
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("操作成功");*/


    //后台管理端

    //查询所有订单
    //1.MyBatisPlus分页查询拦截器已经配置
    //2.根据当前页码和每页显示条数 对category表进行分页查询
    @GetMapping("/page")
    public R<Page> page(@RequestParam(defaultValue="1") int page, @RequestParam(defaultValue="10") int pageSize,String number,String beginTime,String endTime){
        //1.调用service处理
        //页面构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //创建所有order表信息
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        //查询number
        if (number != null){
            wrapper.like(Orders::getNumber,number);
        }

        //查询大于beginTime的时间
        if (beginTime != null){
            wrapper.ge(Orders::getOrderTime,beginTime);
        }

        //查询小于endTime的时间
        if (endTime != null){
            wrapper.lt(Orders::getOrderTime,endTime);
        }

        //根据订单时间排序
        wrapper.orderByAsc(Orders::getOrderTime);

        orderService.page(ordersPage,wrapper);

        //2.响应处理结果
        return R.success(ordersPage);
    }

    //订单状态修改
    @PutMapping
    public R<String> order(@RequestBody Orders orders){
        log.info("orders:{}",orders);
        Orders order = orderService.getById(orders.getId());
        if (order.getStatus()==2){
            orders.setStatus(3);
            orderService.updateById(orders);
            return R.success("订单派送成功！");
        }else {
            orders.setStatus(4);
            orderService.updateById(orders);
            return R.success("订单已完成！");
        }
    }


}
